package usesynchronized;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 74646
 * Date: 2022-05-08
 * Time: 8:27
 */
class Counter1 {
    // 自增变量
    public int count;

    /**
     * 使用 synchronized 修饰普通方法（increase方法）
     * 进入方法就加锁，退出方法就解锁
     */
    synchronized public void increase(){
        count++;
    }
}

public class Demo1 {
    private static Counter1 counter1 = new Counter1();

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter1.increase();
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter1.increase();
            }
        });
        t1.start();
        t2.start();

        /**
         * 因为 main 线程与 t1,t2 线程是并发执行的，会导致 t1,t2 线程还没执行完就执行下面的打印操作
         * 为了保证 t1,t2 线程都执行完了再打印 count，
         * 所以调用 join 方法，等待 t1,t2 线程都执行完了再打印
         */
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(counter1.count);
    }
}
